package com.nnnu.wsnackshop.controller.admin;


import com.nnnu.wsnackshop.constant.MessageConstants;
import com.nnnu.wsnackshop.pojo.dto.AssignUserRoleDTO;
import com.nnnu.wsnackshop.pojo.vo.RoleVO;
import com.nnnu.wsnackshop.pojo.vo.UserRoleVO;
import com.nnnu.wsnackshop.result.Result;
import com.nnnu.wsnackshop.service.IUserRolesService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 用户-角色关联 前端控制器
 * </p>
 *
 * @author zk
 * @since 2025-05-14
 */
@RestController("adminUserRolesController")
@RequestMapping("/api/admin/user-roles")
@Slf4j
@Validated
@Tag(name = "管理端用户角色接口")
@RequiredArgsConstructor
public class UserRolesController {

    private final IUserRolesService userRolesService;

    @Operation(summary = "查询用户已分配角色", description = "仅 superAdmin 或 admin 且拥有 user:read 权限可访问")
    @GetMapping("/{userId}")
    @RequiresRoles(value = {"superAdmin","admin"}, logical = Logical.OR)
    @RequiresPermissions("user:read")
    public Result<UserRoleVO> getUserRoles(
            @PathVariable @Parameter(description = "用户 ID", in = ParameterIn.PATH) Long userId) {
        log.info("查询用户已分配角色：{}", userId);
        return Result.success(userRolesService.getUserRoles(userId),MessageConstants.SELECT_OK);
    }

    @Operation(summary = "管理员分配角色给用户", description = "仅 superAdmin 或 admin 且拥有 user:assign_roles 权限可访问")
    @PostMapping
    @RequiresRoles(value = {"superAdmin","admin"}, logical = Logical.OR)
    @RequiresPermissions("user:assign_roles")
    public Result<?> assignRoles(
            @Valid @RequestBody @Parameter(description = "用户角色信息") AssignUserRoleDTO dto) {
        log.info("管理员分配角色给用户：{}", dto);
        userRolesService.assignRoles(dto);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }

    @Operation(summary = "查询所有角色", description = "超级管理员可查看所有角色，普通管理员只能查看低级角色")
    @GetMapping
    @RequiresRoles(value = {"superAdmin", "admin"}, logical = Logical.OR)
    @RequiresPermissions("role:read")
    public Result<List<RoleVO>> listRoles() {
        log.info("查询角色列表");
        return Result.success(userRolesService.listRoles(), MessageConstants.SELECT_OK);
    }

}
